<?php
session_start();
require_once 'database.php';
header('Content-Type: application/json');

function default_response($data = [], $status = 'success', $code = 200)
{
    http_response_code($code);
    echo json_encode(array_merge(['status' => $status], $data));
}

// 新增的查询函数
function getTrainingCostData($school, $start_time, $end_time)
{
    global $pdo;

    $sql = "SELECT 
            t.id,
            t.department,
            t.title,
            t.start_time,
            t.end_time,
            t.location,
            count(tt.teacher_name) AS people,
            group_concat(tt.teacher_name, '，') AS teacher_list,
            t.type
         FROM trainings t
         LEFT JOIN trainings_teachers tt ON t.id = tt.training_id
         WHERE " . ($school === '所有单位' ? '' : 'tt.teacher_school = ? AND ') . "t.start_time BETWEEN ? AND ?
         GROUP BY t.id";

    // 查询trainings_teachers表和trainings表
    $stmt = $pdo->prepare($sql);

    if ($school == '所有单位') {
        $stmt->bindParam(1, $start_time, PDO::PARAM_STR);
        $stmt->bindParam(2, $end_time, PDO::PARAM_STR);
    } else {
        $stmt->bindParam(1, $school, PDO::PARAM_STR);
        $stmt->bindParam(2, $start_time, PDO::PARAM_STR);
        $stmt->bindParam(3, $end_time, PDO::PARAM_STR);
    }
    if ($stmt->execute()) {
        $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $training_ids = array_column($data, 'id');
        // 根据$training_ids查询trainings_cost表，获取cost和other_cost，汇总cost和other_cost，并添加到data中
        $sql = "SELECT 
                trainings_id AS id,
                SUM(cost) AS cost,
                SUM(other_cost) AS other_cost
            FROM trainings_cost
            WHERE " . ($school === '所有单位' ? '' : 'school = ? AND ') . "trainings_id IN (" . implode(',', $training_ids) . ")
            GROUP BY trainings_id";
        $stmt = $pdo->prepare($sql);
        if ($school != '所有单位') {
            $stmt->bindParam(1, $school, PDO::PARAM_STR);
        }
        $stmt->execute();
        $training_cost = $stmt->fetchAll(PDO::FETCH_ASSOC);
        // 根据$data的id和$training_cost的trainings_id进行匹配，将$training_cost中的cost和other_cost字段合并到$data中
        foreach ($data as &$item) {
            foreach ($training_cost as $cost_item) {
                if ($item['id'] == $cost_item['id']) {
                    $item['cost'] = $cost_item['cost'];
                    $item['other_cost'] = $cost_item['other_cost'];
                    break;
                }
            }
        }
        return $data;
    }
    return false;
}

try {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // 新增的数据查询逻辑
        if (isset($_POST['school']) && isset($_POST['start_time']) && isset($_POST['end_time'])) {
            $data = getTrainingCostData($_POST['school'], $_POST['start_time'], $_POST['end_time']);
            if ($data !== false) {
                default_response(["data" => $data]);
            } else {
                default_response(["message" => "没有找到相关数据"], "error", 404);
            }
        } else {
            default_response(["message" => "缺少必要的参数" . $_POST], "error", 400);
        }
    } else {
        default_response(["message" => "无效的请求方法"], "error", 405);
    }
} catch (Exception $e) {
    default_response(["message" => $e->getMessage()], "error", 500);
}